package com.javaee.ejb.session;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.javaee.ejb.entity.Conversation;
import com.javaee.ejb.entity.Employee;

/**
 * Session Bean implementation class ConversationManager
 */
@Stateless
public class ConversationManager implements ConversationManagerRemote {

    /**
     * Default constructor. 
     */
	@PersistenceContext
	EntityManager m_GestionnairesEntities;
	
	public ConversationManager() {
        // TODO Auto-generated constructor stub
    }

	@Override
	public void ajouterConversation(Conversation c_Conversation) {
		m_GestionnairesEntities.persist(c_Conversation);
	}
	
	public Conversation getConversation(int caller, int called)
    {
    		Query q =	m_GestionnairesEntities.createNamedQuery("FindConversation").setParameter("p_callerid", caller).setParameter("p_calledid", called);
    		Conversation c = null;
    		try
    		{
    			c = (Conversation) q.getSingleResult();
    			return c;
    		}
    		catch(Exception e){
    			try{
    			q =	m_GestionnairesEntities.createNamedQuery("FindConversation").setParameter("p_callerid", called).setParameter("p_calledid", caller);
        		c = (Conversation) q.getSingleResult();
        		return c;
    			}
    			catch(Exception ex){
    				Conversation conv = new Conversation();
    				conv.setCallerId(caller);
    				conv.setCalledId(called);
    				this.ajouterConversation(conv);
    				return conv;
    				
    			}
    		}    		
    }

}
